# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

import glib
import gobject
import gtk
import os
import tempfile

from pkg_resources import resource_string
from main import DATA_DIR

def get_pixbuf_from_data(data, size = None):
    """get a pixbuf from data string
    When loading images from eggs, gtk.gdk.Pixbuf cannot be created
    using file descriptor, so we use temporary files
    """
    temp_file = tempfile.NamedTemporaryFile()
    temp_file.write(data); temp_file.flush()
    try:
        if size == None:
            pixb = gtk.gdk.pixbuf_new_from_file(temp_file.name)
        else:
            pixb = gtk.gdk.pixbuf_new_from_file_at_size(temp_file.name, size[0], size[1])
    except gobject.GError:
        if size == None:
            size = (128, 128)
        pixb = gtk.icon_theme_get_default().load_icon('etude', size[0], 0)
    temp_file.close()
    return pixb

def get_data_from_pixbuf(pixbuf):
    """get data from a pixbuf
    Useful when sending albumart to the server, after resizing the pixbuf
    """
    temp_file = tempfile.NamedTemporaryFile()
    pixbuf.save(temp_file.name , 'jpeg', {'quality': '100'})
    temp_file.flush()
    ret_data = temp_file.read()
    print(len(ret_data))
    return ret_data

def load_svg_from_egg(package, path, size = None):
    data = resource_string(package, path)
    t = tempfile.NamedTemporaryFile(suffix='.svg')
    t.write(data); t.flush()
    if size == None:
        pixb = gtk.gdk.pixbuf_new_from_file(t.name)
    else:
        pixb = gtk.gdk.pixbuf_new_from_file_at_size(t.name, size[0], size[1])
    t.close()
    return pixb

def valid_image(filename):
    """
    check if the image is valid
    """
    return bool(gtk.gdk.pixbuf_get_file_info(filename))

def get_pixbuf_of_size(pixbuf, size):
	"""
    Create a pixbuf that fits in the specified square of sizexsize
	while preserving the aspect ratio
	Returns tuple: (scaled_pixbuf, actual_width, actual_height)
    """
	image_width = pixbuf.get_width()
	image_height = pixbuf.get_height()
	if image_width > image_height:
		if image_width > size:
			image_height = int(size/float(image_width)*image_height)
			image_width = size
	else:
		if image_height > size:
			image_width = int(size/float(image_height)*image_width)
			image_height = size
	crop_pixbuf = pixbuf.scale_simple(image_width, image_height, gtk.gdk.INTERP_HYPER)
	return (crop_pixbuf, image_width, image_height)

def register_iconsets(icon_info):
    iconfactory = gtk.IconFactory()
    stock_ids = gtk.stock_list_ids()
    for stock_id, file in icon_info:
        # only load image files when our stock_id is not present
        if stock_id not in stock_ids:
            pixbuf = gtk.gdk.pixbuf_new_from_file(file)
            iconset = gtk.IconSet(pixbuf)
            iconfactory.add(stock_id, iconset)
    iconfactory.add_default()

_ICONS = [
        ('etude', 'etude.svg'),
        ('etude-tray-icon', 'etude.svg'),
        ('etude-tray-play', 'etude-tray-play.svg'),
        ('etude-tray-pause', 'etude-tray-pause.svg'),
        ('etude-plugin-extra', 'etude-plugin-extra.svg'),
        ('etude-plugin-panel', 'etude-plugin-panel.svg')
        ]

def register_stock_icons():

    icon_theme = gtk.icon_theme_get_default()
    icon_theme.append_search_path(DATA_DIR)
    icons = [(name, os.path.join(DATA_DIR, filename)) 
            for name, filename in _ICONS]
    register_iconsets(icons)

